package org.kepler.chat.api.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.bigdata.frame.exception.BizException;
import org.bigdata.frame.util.ReturnDatas;
import org.kepler.chat.api.entity.User;
import org.kepler.chat.api.infra.util.ErrorCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/rest/user")
public class UserApi extends BaseApi {

    @ApiOperation(value = "获取当前登录用户信息", notes = "获取当前登录用户信息")
    @RequestMapping(value = "/session", method = RequestMethod.GET)
    public ReturnDatas session(HttpServletRequest request) {
        ReturnDatas returnDatas = ReturnDatas.getSuccessReturnDatas();

        User user = getLoginUser(request);
        if (null == user) {
            throw new BizException(ErrorCode.USER_NOT_EXIST.getCode(), ErrorCode.USER_NOT_EXIST.getMessage());
        }
        String gender = "";
        if (user.getGender() != null) {
            gender = user.getGender().equals("1") ? "男" : "女";
        }
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("userId", user.getId());
        userMap.put("username", user.getName());
        userMap.put("sex", gender);
        userMap.put("role", user.getRoleid());

        returnDatas.setData(userMap);
        return returnDatas;
    }

    @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息")
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ReturnDatas getUser(@RequestParam("uid") @ApiParam(value = "用户ID", required = true) int uid) {
        ReturnDatas returnDatas = ReturnDatas.getSuccessReturnDatas();

        User user = userService.findUserById(uid);
        if (null == user) {
            throw new BizException(ErrorCode.USER_NOT_EXIST.getCode(), ErrorCode.USER_NOT_EXIST.getMessage());
        }
        String gender = "";
        if (user.getGender() != null) {
            gender = user.getGender().equals("1") ? "男" : "女";
        }
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("userId", user.getId());
        userMap.put("username", user.getLogin_name());
        userMap.put("sex", gender);
        userMap.put("role", user.getRoleid());

        returnDatas.setData(userMap);
        return returnDatas;
    }
}
